package com.cr.framework.web.service;

import com.cr.business.domain.TbUserBaseInfo;
import com.cr.business.mapper.TbUserBaseInfoMapper;
import com.cr.common.core.domain.entity.AppUser;
import com.cr.common.core.domain.model.AppLoginUser;
import com.cr.common.exception.ServiceException;
import com.cr.common.utils.MessageUtils;
import com.cr.common.utils.StringUtils;
import com.cr.common.utils.bean.BeanUtils;
import org.slf4j.Logger;
import org.slf4j.LoggerFactory;
import org.springframework.security.core.userdetails.UserDetails;
import org.springframework.security.core.userdetails.UserDetailsService;
import org.springframework.security.core.userdetails.UsernameNotFoundException;
import org.springframework.stereotype.Service;

import javax.annotation.Resource;
import java.util.HashSet;
import java.util.Set;

/**
 * app用户验证处理
 *
 */
@Service("appUserDetailsService")
public class AppUserDetailsServiceImpl implements UserDetailsService
{
    private static final Logger log = LoggerFactory.getLogger(AppUserDetailsServiceImpl.class);

    @Resource
    private TbUserBaseInfoMapper tbUserBaseInfoMapper;

    @Override
    public UserDetails loadUserByUsername(String username) throws UsernameNotFoundException
    {
        TbUserBaseInfo tbUserBaseInfo = tbUserBaseInfoMapper.selectUserByPhone(username);
        if (StringUtils.isNull(tbUserBaseInfo))
        {
            log.info("登录用户：{} 不存在.", username);
            throw new ServiceException(MessageUtils.message("user.not.exists"));
        }
        else if ("2".equals(tbUserBaseInfo.getStatus()))
        {
            log.info("登录用户：{} 已被停用.", username);
            throw new ServiceException(MessageUtils.message("user.blocked"));
        }

        AppUser user = new AppUser();
        BeanUtils.copyBeanProp(user, tbUserBaseInfo);
        return createLoginUser(user);
    }

    public UserDetails createLoginUser(AppUser user)
    {
        Set<String> perms = new HashSet<>();
        perms.add("*:*:*");
        return new AppLoginUser(user.getUserId(), user, perms);
    }
}
